﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Red.GameData.Raw
{
    partial class DataCollection
    {
        /// <summary>
        /// Load a whole collection of data from an environment
        /// </summary>
        /// <param name="log">All errors and progress tracking are reported through this interface</param>
        /// <param name="path">Absolute path to load files from</param>
        /// <returns></returns>
        public static DataCollection Create(IGenericFileErrorReporter log, string rootPath)
        {
            // create the fresh, new object collection
            DataCollection ret = new DataCollection(rootPath);

            // load files
            try
            {
                string[] files = Directory.GetFiles(rootPath, "*.xml", SearchOption.AllDirectories);

                int fileIndex = 0;
                foreach (string filePath in files)
                {
                    // report file progress
                    log.StartFile( filePath );
                    log.TotalProgress( fileIndex++, files.Length );

                    // try to load the data file
                    DataFile dataFile = new DataFile( ret, filePath );
                    dataFile.Reload(log);
                    ret.AllFiles.Add(dataFile);
                }
            }
            catch (Exception e)
            {
                log.Error("Fatal loading exception:\r\n" + e.ToString());
            }

            // regenerate the mappings
            ret.RegenerateObjectMap();
            return ret;
        }

        // create/get file
        public DataFile Action_CreateFile(IGenericFileErrorReporter log, string path)
        {
            // get from existing files
            foreach (DataFile f in AllFiles)
                if (f.Path == path)
                    return f;

            // create new file
            var newFile = new DataFile(this, path);

            // save the file (will save empty file stub onto the disk)
            try
            {
                newFile.Save(log, /*force*/true );
            }
            catch (Exception e)
            {
                log.Error(String.Format("Fatal error creating a new file:\n\r") + e.ToString());
                return null; // something went wrong
            }

            // add to global list
            AllFiles.Add(newFile);
            return newFile;
        }
    }
}
